package com.android.gl2jni.filter;

import static com.android.gl2jni.filter.TextureFilterProgram.ProgramType.TEXTURE_EXT;

import android.content.Context;
import android.opengl.GLES20;
import com.android.gl2jni.ShaderUtils;

/**
 * Create time: 2018/9/15.
 */
public class BeautifyFilterProgram extends TextureFilterProgram {
  private int opacityLoc;
  private int widthLoc;
  private int heightLoc;
  private float opacity;

  /**
   * Prepares the program in the current EGL context.
   */
  public BeautifyFilterProgram(Context context) {
    super(context, TEXTURE_EXT);
  }

  @Override
  protected String getFragmentShaderSourceEXT() {
    return ShaderUtils.readAssetsTextFile(getContext(),
        "filter/fsh/beautify/beautify.glsl");
  }

  @Override
  protected void initProgram() {
    super.initProgram();
    opacityLoc = getUniformLocation("opacity");
    widthLoc = getUniformLocation("width");
    heightLoc = getUniformLocation("height");
  }

  @Override
  protected void onDraw(int firstVertex, int vertexCount) {
    setInt(widthLoc, surfaceWidth);
    setInt(heightLoc, surfaceHeight);
    setFloat(opacityLoc, opacity);
    super.onDraw(firstVertex, vertexCount);
  }

  /**
   * 设置磨皮程度
   * @param percent 百分比
   */
  public void setSmoothOpacity(float percent) {
    if (percent <= 0) {
      opacity = 0.0f;
    } else {
      opacity = calculateOpacity(percent);
    }
  }

  /**
   * 根据百分比计算出实际的磨皮程度
   * @param percent
   * @return
   */
  private float calculateOpacity(float percent) {
    float result;

    // TODO 可以加入分段函数，对不同等级的磨皮进行不一样的处理
    result = (float) (1.0f - (1.0f - percent + 0.02) / 2.0f);

    return result;
  }
}
